<template>
  <div>
    <el-upload
      style="width: 100%"
      ref="importFileUploader"
      :action="importFileUrl"
      :headers="uploadHeaders"
      accept=".xls,.xlsx"
      :multiple="false"
      :before-upload="beforeUpload"
      :on-success="handleUploadSuccess"
      :data="upLoadData"
      :auto-upload="false"
      name="file"
      :limit="1"
    >
      <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
      <el-button size="mini" type="success" @click="submitUpload"
        >导入</el-button
      >
    </el-upload>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";

export default {
  name: "excelUpload",
  props: {
  },
  data() {
    return {
      upLoadData: {
        departmentId: "111111111112",
      },
      importFileUrl: `${process.env.BASE_API}/dms/meal/import`,
      uploadHeaders: {
        Authorization: getToken(),
      },
    };
  },
  computed: {},
  methods: {
    beforeUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!extension && !extension2) {
        this.$message.error("导入文件只支持xls和xlsx文件");
        this.$refs.importFileUploader.clearFiles();
      }
      if (!isLt50M) {
        this.$message.error("导入文件小于50M");
        this.$refs.importFileUploader.clearFiles();
      }
    },
    handleUploadSuccess(res, file) {
      if (res.code === "0-0-0-0-0-0") {
        this.$message({
          message: "导入成功",
          type: "info",
        });
        // ...
      } else {
        this.$message({
          message: res.message,
          type: "error",
        });
      }
    },
    submitUpload() {
      this.$confirm("确定要导入吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          if (this.$refs.importFileUploader.uploadFiles.length === 0) {
            this.$message.info("没有选择文件");
            return false;
          }
          if (this.$refs.importFileUploader.uploadFiles.length > 1) {
            this.$message.info("只能上传1个文件");
            this.$refs.importFileUploader.clearFiles();
            return false;
          }
          // 这边是真正触发上传的地方
          this.$refs.importFileUploader.submit();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已终止导入",
          });
          return false;
        });
    },
  },
};
</script>
<style>
</style>


